<template>
    <div>
    <el-dialog v-model="dialogVisible" width="80%" align-center :show-close="false" @close="handleClose" draggable destroy-on-close>
        <template #header="{ close }">
            <div class="dialog-header flex justify-between items-center">
                <div>{{ title }}</div>
                <el-icon class="el-icon--left cursor-pointer" @click="close">
                    <CircleCloseFilled color="#fff" />
                </el-icon>
            </div>
        </template>
        <div class="bg-white my-[10px]">
            <BaseHead>基本信息</BaseHead>
            <div class="p-[10px]">
                <el-form :model="ProjectIncomeShow" label-width="130px" ref="claimProjectShowRef">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="项目名称">
                                <el-select ref="selectRef" v-model="ProjectIncomeShow.projectName" clearable
                                    popper-class="t-select-table" filterable :filter-method="getprojectList">
                                    <el-table :data="projectList" style="width: 100%" @row-click="handleRowClick">
                                        <el-table-column prop="code" label="项目编号" width="130" />
                                        <el-table-column prop="name" :show-overflow-tooltip="true" label="项目名称" />
                                        <el-table-column prop="chargerName" label="负责人" width="80" />
                                        <el-table-column prop="account" label="负责人工号" width="110" />
                                    </el-table>

                                    <el-option v-show="false" v-for="item in projectList" :key="item.id"
                                        :label="item.name" :value="item.id">
                                    </el-option>
                                    <template #footer><span
                                            style="padding:5px 10px;background-color:#f0f0f0">注：已显示满足条件的前50条记录</span></template>
                                </el-select>

                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="经费卡负责人">
                                {{ ProjectIncomeShow.feeChargerName }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="合同金额"> {{ FloatDiv(ProjectIncomeShow.feeAuthorize, 10000) }}<span> 万元</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="未到金额">
                                {{ ProjectIncomeShow.notIncomeFee }}<span> 万元</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
        <div class="bg-white my-[10px]">
            <BaseHead>到账信息</BaseHead>
            <div class="p-[10px]">
                <el-form :model="ProjectIncomeShow" label-width="130px" ref="claimProjectShowRef">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="来款单位">
                                <el-input v-model="ProjectIncomeShow.incomeUnitName" style="width: 90%" clearable>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="来款类型" v-show="showIncomeType">
                                <el-radio-group v-model="ProjectIncomeShow.incomeType">
                                    <el-radio v-for="item in incomeTypeList" :key="item.code" :value="item.code"
                                        size="large">{{
                                        item.name }}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="本次入账(万元)">
                                <el-input v-model="ProjectIncomeShow.incomeFee" style="width: 90%" clearable
                                    @input="e => checkclaimFee(e)">
                                    <template #append>万元</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="外拨金额">
                                <el-input v-model="ProjectIncomeShow.outboundFee" style="width: 90%" clearable
                                    @input="e => checkoutboundFee(e)">
                                    <template #append>万元</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="留校金额">
                                {{ProjectIncomeShow.schoolFee}} 万元
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="对冲号">
                                <el-input v-model="ProjectIncomeShow.dch" style="width: 90%" clearable>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="到账日期">
                                <el-date-picker v-model="ProjectIncomeShow.incomeDate" type="date"
                                    value-format="YYYY-MM-DD" :clearable="false" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="经费账号">
                                <el-input v-model="ProjectIncomeShow.feeCardNum" style="width: 90%" clearable>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
        <div class="bg-white my-[10px]" v-show="manageShow">
            <BaseHead>管理费信息</BaseHead>
            <BaseTable>
                <tr>
                    <td class="td-subname">管理费信息</td>
                    <td class="td-subname" colspan="3">累计扣除管理费(万元)</td>
                    <td class="td-subname" colspan="3">本次扣除管理费(万元)</td>
                </tr>
                <tr v-for="(items, index) in ProjectIncomeShow.manageFee" :key="index">
                    <td class="td-subname">{{ items.subjectName }}</td>
                    <td colspan="3" > {{ items.splitManageFee }}</td>
                    <td colspan="3" >
                        <el-input v-model="items.subjectFee" style="width: 90%" clearable>
                        </el-input>
                    </td>
                </tr>
            </BaseTable>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <div class="operate-btns">
                    <el-button type="primary" @click="save">保存</el-button>
                    <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
    </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import BaseTable from "@/views/fee/components/BaseTable.vue";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import useCommonFetch from "@/hooks/useCommonFetch";
import { ElMessage } from "element-plus";
import { isMoney,FloatSub,FloatAdd,FloatDiv,FloatMul } from "@/utils/pub";
import { getprojectInfo,addproclaim,editproclaim } from "@/api/fee/rz/jfkrz/index.js";
import { getprolist } from "@/api/fee/rz/yhdk/index.js";
import { formatDate } from '@/utils/formatTime'
import { ref } from "vue";
const dialogVisible = ref(false);
const manageShow = ref(false);//管理费展示
const showIncomeType = ref(true);//来款类型展示
const incomeTypeList = useCommonFetch("来款类型");
var projectId = "";//项目号
const projectList= ref([]);//项目list
const ProjectIncomeShow = ref({id:""});
const selectRef = ref(null);//选中项目弹窗
const title = computed(() => {
  return ProjectIncomeShow.value.id == null ? "经费卡入账新增" :"经费卡入账编辑";
});

const edit = async (row) => {
    dialogVisible.value = true;
    handleclear();
    if(row != null && row != ""){
        ProjectIncomeShow.value = row;
        projectId = row.projectId;
        initProjectInfo(row.projectId,row.id);
    }
};

defineExpose({edit});
const emit = defineEmits(["save-success"]);

//获取项目列表
const getprojectList = async (queryString) => {
    const params = {
        pageNum: 1,
        pageSize: 50, name: queryString
    };
    try {
        const res = await getprolist(params);
        if (res.code == 200) {
            projectList.value = res.rows;
        }
    } catch (error) {
        console.log(error);
    }
}
onMounted(() => {
    getprojectList();
});

//选中项目
const handleRowClick = (row) =>{
    //先清空
    handleclear();
    selectRef.value.blur();
    projectId = row.projectId;
    initProjectInfo(row.id); //初始化数据  
    initIncomeType();
}

/**
 * 初始化到账类型，
 * 横向项目没有到账类型，纵向有，一般校级管理按照纵向管理
 * 
 */
 function initIncomeType(){
    if (ProjectIncomeShow.value.projectClass == 'yfContract') { // 横向项目
        showIncomeType.value = false;
		ProjectIncomeShow.value.incomeType= "mixed";
	}else{
        showIncomeType.value = true;
    }
}

//初始化数据
const initProjectInfo = async (projectId,projectIncomeId)=>{
    let params = {projectId:projectId,projectIncomeId:projectIncomeId};
    try {
        const res = await getprojectInfo(params);
        if (res.code == 200) {
            ProjectIncomeShow.value = res.data;
            ProjectIncomeShow.value.incomeType = res.data.id == null?"mixed":res.data.incomeType;
            ProjectIncomeShow.value.incomeFee = FloatDiv(res.data.incomeFee,10000);
            ProjectIncomeShow.value.outboundFee = FloatDiv(res.data.outboundFee,10000);
            ProjectIncomeShow.value.schoolFee = FloatDiv(res.data.schoolFee,10000);
            ProjectIncomeShow.value.notIncomeFee = FloatDiv(res.data.notIncomeFee,10000);
            if(res.data.incomeDate == null ||res.data.incomeDate == "" ){
                ProjectIncomeShow.value.incomeDate = formatDate(new Date(),"YYYY-MM-DD");
            }
            //纵向项目有管理费
            if (res.data.projectClass == "zXProject") {
                manageShow.value = true;
                ProjectIncomeShow.value.manageFee.map(item => {
                    item.subjectFee = FloatDiv(item.subjectFee, 10000);
                    item.splitManageFee = FloatDiv(item.splitManageFee, 10000);
                });
            }
           
        }
    }catch (error) {
        console.log(error);
    }
}

//检查认领经费
const checkclaimFee = (value)=>{
    if (projectId == "") {
        ElMessage.error("请先选择项目！");	
		ProjectIncomeShow.value.incomeFee="";
		return false;
	}
    // if(!isNum(value)){
    //     ElMessage.error("请输入数字");
    //     claimShow.value.claimFee = "";
    //     return false;
    // }
    if (parseFloat(value) > 100000) {
        ElMessage.error("单笔金额不能超过10亿");
        ProjectIncomeShow.value.incomeFee = "";
        return false;
    }
    
    if (!isMoney(value)) {
        ElMessage.error("金额小数位不能超过6位，只能精确到分");	
        ProjectIncomeShow.value.incomeFee="";
		return false;
    } 
    if (parseFloat(value) > parseFloat(ProjectIncomeShow.value.notIncomeFee)) {
        ElMessage.error('本次到账金额不能大于未到账金额！');	
		ProjectIncomeShow.value.incomeFee="";
		return false;
	}
    ProjectIncomeShow.value.schoolFee = value!=''?value:0;
    if (ProjectIncomeShow.value.projectClass == 'zXProject') {
        ProjectIncomeShow.value.manageFee.map(item => {
            if (item.subjectName != "") {
                if (value != null && value != '') {
                    item.subjectFee = FloatMul(value,0.05);
                    } else {
                        item.subjectFee = 0;
                    }   
            }
        });
    }
}

//检查外拨经费
const checkoutboundFee = (value)=>{
    // if(!isNum(value)){
    //     ElMessage.error("请输入数字");
    //     claimShow.value.outboundFee = "";
    //     return false;
    // }
    if (value > 100000) {
        ElMessage.error("单笔金额不能超过10亿");
        ProjectIncomeShow.value.outboundFee = "";
        return false;
    }
    
    if (!isMoney(value)) {
        ElMessage.error("金额小数位不能超过6位，只能精确到分");	
        ProjectIncomeShow.value.outboundFee="";
		return false;
    } 
    var canOutboundFee = ProjectIncomeShow.value.notOutFee; // 可外拨金额
    if (parseFloat(value) > parseFloat(canOutboundFee)) {
		ElMessage.error("外拨金额不能超过"+canOutboundFee+"万元！");	
        ProjectIncomeShow.value.outboundFee="";
		return false;
	}
    if (parseFloat(value) > parseFloat(ProjectIncomeShow.value.incomeFee)) {
		ElMessage.error("外拨金额不能超过认领金额！");	
        ProjectIncomeShow.value.outboundFee="";
		return false;
	}
    ProjectIncomeShow.value.schoolFee= FloatSub(ProjectIncomeShow.value.incomeFee,value);

}

//清空
const handleclear =() =>{
    projectId = "";
    manageShow.value = false;
    showIncomeType.value = true;
    ProjectIncomeShow.value={};
}

//保存前验证及处理数据
const beforesave = ()=>{
    if (!projectId) {
        ElMessage.error("未选择要认领的项目！");
		return false;
	}
    if(ProjectIncomeShow.value.incomeUnitName =="" || ProjectIncomeShow.value.incomeUnitName === null ){
        ElMessage.error("请填写来款单位！");
		return false;
   }
   if(Number(ProjectIncomeShow.value.incomeFee) <=0){
        ElMessage.error("请填写本次入账金额！");
		return false;
   }
}

//处理金额
const handleMoney =(params)=>{
    params.incomeFee = FloatMul(ProjectIncomeShow.value.incomeFee,10000);
    params.outboundFee = FloatMul(ProjectIncomeShow.value.outboundFee,10000);
    params.schoolFee = FloatMul(ProjectIncomeShow.value.schoolFee,10000);
    
    if (ProjectIncomeShow.value.projectClass == 'zXProject') {
        params.manageFee.map(item => {
            item.subjectFee = FloatMul(item.subjectFee, 10000);
            item.splitManageFee = FloatMul(item.splitManageFee, 10000);
        });
    }
}


//点击保存
const save = async() => {
  try {
    beforesave();//保存前校验
    let params = {...ProjectIncomeShow.value, checkstatus:2}; 
    console.log(params);
    handleMoney(params);
   const res=ref(null);
   if(params.id != "" && params.id != null){
     res.value = await editproclaim(params);
   }else{
    res.value = await addproclaim(params);
   }
   
    if (res.value.code === 200) {
        ElMessage({ message: "操作成功！",type: "success",});
        dialogVisible.value = false;
        handleclear();
        emit("save-success");
    }
  } catch (error) {
    console.log(error);
  }
};


//关闭弹窗
const handleClose = () => {
  
};

</script>

<style scoped lang="scss">
@import url("@/views/fee/index.scss");
</style>